package cn.antalk.top.user.controller;

import cn.antalk.top.user.entity.User;
import cn.antalk.top.user.entity.UserLikeTalk;
import cn.antalk.top.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: WackyBoy
 * @Date: 2021/12/6 20:08
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/query")
    public ResponseEntity<User> queryUser(@RequestParam("uname") String uname, @RequestParam("password") String password) {
            User user = this.userService.queryUserByAll(uname, password);
            if(user == null) return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            return ResponseEntity.ok(user);
    }

    @GetMapping("/login")
    public ResponseEntity<UserLikeTalk> loginUser(@RequestParam("uname") String uname, @RequestParam("password") String password) {
        UserLikeTalk user = this.userService.queryUserForLogin(uname, password);
        if(user == null) return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        return ResponseEntity.ok(user);
    }

    @PostMapping("/register")
    public ResponseEntity register (@RequestParam("uname") String uname, @RequestParam("password") String password) {
        ResponseEntity<User> responseEntity = queryUser(uname, password);
        if(responseEntity.getStatusCode().is2xxSuccessful()) {
            // 409 Conflict
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }
        Boolean isRegister = this.userService.register(uname, password);
        if(isRegister == null || !isRegister) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

}
